package com.service;

import com.entity.WeiJianProjectInfo;
import com.repository.WeiJianDispatchRecordRepository;
import com.repository.WeiJianProjectInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
@Transactional
public class WeiJianProjectInfoService {

    @Autowired
    private WeiJianProjectInfoRepository weiJianProjectInfoRepository;

    @Autowired
    private WeiJianDispatchRecordRepository weiJianDispatchRecordRepository;

    /**
     * 保存项目信息
     * @param weiJianProjectInfo 项目信息
     * @return 保存后的对象
     */
    public WeiJianProjectInfo save(WeiJianProjectInfo weiJianProjectInfo) {
        if (weiJianProjectInfo.getId() == null) {
            weiJianProjectInfo.setCreateTime(new Date());
        }
        weiJianProjectInfo.setUpdateTime(new Date());
        return weiJianProjectInfoRepository.save(weiJianProjectInfo);
    }

    /**
     * 根据ID删除项目信息
     * @param id ID
     */
    public void deleteById(Integer id) {
        weiJianProjectInfoRepository.findById(id).ifPresent(projectInfo -> {
            weiJianDispatchRecordRepository.deleteAllByProjectName(projectInfo.getProjectName());
        });
        weiJianProjectInfoRepository.deleteById(id);
    }

    /**
     * 根据ID获取项目信息
     * @param id ID
     * @return 项目信息
     */
    @Transactional(readOnly = true)
    public Optional<WeiJianProjectInfo> findById(Integer id) {
        return weiJianProjectInfoRepository.findById(id);
    }

    /**
     * 分页查询项目信息
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<WeiJianProjectInfo> findAll(int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return weiJianProjectInfoRepository.findAll(pageable);
    }

    /**
     * 根据项目名称模糊查询项目信息
     * @param projectName 项目名称
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @return 分页结果
     */
    @Transactional(readOnly = true)
    public Page<WeiJianProjectInfo> findByProjectNameContaining(String projectName, int pageNum, int pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "createTime"));
        return weiJianProjectInfoRepository.findByProjectNameContaining(projectName, pageable);
    }
}